import { useState, useEffect } from "react";
import { Select, Spin, Empty } from "antd";
import { getObjectFinalValue } from "@src/tools/commonTool";

interface fieldNamesProp {
	label: string;
	value: string;
}
interface CommonSearchSelectProp {
	placeholder?: string;
	mode?: any;
	style?: object;
	labelInValue?: boolean;
	fieldNames?: fieldNamesProp;
	fieldType?: string;
	SearchFunc?: any;
	allowClear?: boolean;
	onChange?: any;
	value?: any;
	preSearchParam?: object;
}

let searchTimer: any = null;

function CommonSearchSelect(props: CommonSearchSelectProp) {
	const {
		placeholder = "请搜索并选择下拉内容",
		mode = "",
		style = { width: "150px" },
		labelInValue = false,
		SearchFunc,
		allowClear = true,
		fieldNames = { label: "label", value: "value" },
		onChange = () => {},
		preSearchParam = {},
	} = props;
	const [fetching, setFetching] = useState(false);
	const [options, setOptions] = useState([]);
	const [value, setValue] = useState(
		mode === "multiple" ? [] : (null as any)
	);

	useEffect(() => {
		if (!props.hasOwnProperty("value")) {
			return;
		}
		setValue(props.value || (mode === "multiple" ? [] : null));
	}, [props, mode]);

	const search = (str: string) => {
		let name = str.trim();
		clearTimeout(searchTimer);
		searchTimer = setTimeout(() => {
			let param = { name, pageSize: 300, pageNum: 1, ...preSearchParam };
			setFetching(true);
			SearchFunc(param)
				.then((res: any) => {
					let newOptions = [...options];
					let theArr = getObjectFinalValue(res, "data.data");
					if (!!theArr) {
						newOptions = theArr.map((item: any) => {
							return {
								label: item[fieldNames.label],
								value: item[fieldNames.value],
							};
						});
					} else {
						newOptions = res.data.map((item: any) => {
							return {
								label: item[fieldNames.label],
								value: item[fieldNames.value],
							};
						});
					}
					setOptions(newOptions);
					setFetching(false);
				})
				.catch(() => {
					setFetching(false);
				});
		}, 500);
	};
	const changeValue = (value: any) => {
		setValue(value || (mode === "multiple" ? [] : null));
		onChange(value || (mode === "multiple" ? [] : null));
	};
	return (
		<Select
			showSearch
			allowClear={allowClear}
			mode={mode}
			style={style}
			value={value}
			onSearch={search}
			onChange={changeValue}
			labelInValue={labelInValue}
			filterOption={false}
			placeholder={placeholder}
			notFoundContent={
				fetching ? (
					<Spin />
				) : (
					<Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
				)
			}
			dropdownRender={(menu) => <div>{menu}</div>}
		>
			{options.map((item: any) => {
				return (
					<Select.Option key={item.value} value={item.value}>
						{item.label}
					</Select.Option>
				);
			})}
		</Select>
	);
}

export default CommonSearchSelect;
